package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.CateGoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时插入菜品的口味数据，需要操作两张表：dish dishFlavor
     *
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
//      1.  保存菜品的基本信息到dish
        this.save(dishDto);

//        菜品的id
        Long dishId = dishDto.getId();

//        菜品口味集合
        List<DishFlavor> flavors = dishDto.getFlavors();
//        把菜品的id放入dishFlavor中
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
//       2. 保存菜品口味到dishFlavor
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getBYIdWithFlavor(Long id) {
//        查菜品基本信息dish
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
//       1. 拷贝普通属性
        BeanUtils.copyProperties(dish, dishDto);

//        查口味信息dishFlavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
//  2.设置增加的口味属性
        dishDto.setFlavors(list);
        return dishDto;

    }

    /**
     * 更新dish基本信息和dishFlavor的口味
     *
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish的基本信息
        this.updateById(dishDto);

        //清理当前菜品的口味数据delete
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据insert
        List<DishFlavor> flavors = dishDto.getFlavors();
        //插入dish_id
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }
}
